package com.easy.common.util;

import org.springframework.util.DigestUtils;

public class PasswordDecode {
    public static final int[] HEX_CHAR_ARR={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
    /**
     * 加密
     * @param pwd
     * @return
     */
    public static String encryption(String pwd){
        //随机次数随机盐值加密
        int countIndex=(int)(Math.random()*HEX_CHAR_ARR.length);
        int saltIndex=(int)(Math.random()*HEX_CHAR_ARR.length);
        int count=HEX_CHAR_ARR[countIndex];
        char salt=(char)HEX_CHAR_ARR[saltIndex];
        char countChar=(char)count;
        pwd=pwd+salt;
        for(int i=0;i<count;i++){
            pwd= DigestUtils.md5DigestAsHex(pwd.getBytes());
        }

        String passwordText=salt+pwd+countChar;
        return passwordText;
    }
    public static boolean decode(String pass,String hexPass){
        char salt=hexPass.charAt(0);
        char countChar=hexPass.charAt(hexPass.length()-1);
        pass=pass+salt;
        for(int i=0;i<countChar;i++){
            pass=DigestUtils.md5DigestAsHex(pass.getBytes());
        }
        String text=salt+pass+countChar;
        return text.equals(hexPass);
    }

    public static void main(String[] args) {
        System.out.println(encryption("123123"));
    }
}
